import { reroute } from "../navigations/reroute";
import { BOOTSTRAPPING, LOADING_SOURCE_CODE, MOUNTED, NOT_BOOTSTRAPPED, NOT_LOADED, NOT_MOUNTED, shouldBeActive } from "./app.helper";

const apps = []; // 存储所有的应用

/**
 * 维护应用所有的状态
 * @param {*} appName 应用名字
 * @param {*} loadApp 加载应用
 * @param {*} activeWhen 当激活时会调用 loadApp
 * @param {*} customProps 自定义属性
 */
export function registerApplication(
    appName,loadApp,activeWhen,customProps
) {
    apps.push({
        name: appName,
        loadApp,
        activeWhen,
        customProps,
        status: NOT_LOADED,
    })
    reroute(); // 加载应用
}
// 获取不同状态的应用队列
export function getAppChanges() {
    const appsToUnmount = []; // 需要卸载的应用
    const appsToLoad = []; // 需要加载的app
    const appsToMount = []; // 需要挂载的应用
    apps.forEach(app=>{
        const appShouldBeActive = shouldBeActive(app);
        switch (app.status) {
            case NOT_LOADED:
            case LOADING_SOURCE_CODE:
                if(appShouldBeActive){
                    appsToLoad.push(app);
                }
                break;
            case NOT_BOOTSTRAPPED:
            case BOOTSTRAPPING:
            case NOT_MOUNTED:
                if (appShouldBeActive) {
                    appsToMount.push(app);
                }
                break;
            case MOUNTED:
                if (!appShouldBeActive) {
                    appsToUnMount.push(app)
                }
            default:
                break;
        }
    })
    return {
        appsToLoad,
        appsToMount,
        appsToUnmount
    }
}